package mess;

import sun.security.util.Length;

public class LeeCode_71 {
    public static void main(String[] args) {
        System.out.println(simplifyPath("/home//foo/"));
        System.out.println(simplifyPath("/../"));
        System.out.println(simplifyPath("/..."));
        System.out.println(simplifyPath("/a/./b/../../c/"));
        System.out.println(simplifyPath("/a/../../b/../c//.//"));
        System.out.println(simplifyPath("/a//b////c/d//././/.."));
        System.out.println(simplifyPath("/."));   //     /
        System.out.println(simplifyPath("/./"));  //     /
        System.out.println(simplifyPath("///eHx/.."));  //  /

    }

    private static String simplifyPath(String path) {
        StringBuilder sb = new StringBuilder(path);
        for (int i = 0; i < sb.length() - 1; i++) {
            // ///
            while (sb.charAt(i) == '/' && sb.charAt(i + 1) == '/'){
                sb.delete(i, i + 1);
                if (sb.length() - 1 - i == 0)
                    break;
            }
            // ??/./??
            if (sb.length() - 1 - i >= 2 && sb.charAt(i) == '/' && sb.charAt(i + 1) =='.' && sb.charAt(i + 2) == '/'){
                sb.delete(i, i + 2);
                i--;
                continue;
            }
            // ??/.
            if (sb.length() - 1 - i == 1 && sb.charAt(i) == '/' && sb.charAt(i + 1) == '.'){
                sb.delete(i + 1, i + 2);
                continue;
            }
            if (sb.length() - 1 - i >= 2){
                // ???/..???
                if (sb.charAt(i) == '/' && sb.charAt(i + 1) == '.' && sb.charAt(i + 2) == '.'){
                    // /..???/
                    if (sb.length() - 1 - i > 2 && sb.charAt(i + 3) != '/'){
                        continue;
                    }
                    // /???/..
                    if (i > 0){
                        int index = i - 1;
                        while (sb.charAt(index) != '/'){
                            index--;
                        }
                        index++;
                        sb.delete(index, i + 3);
                        i = index - 2;
                    }
                    // /..
                    else if (i == 0){
                        sb.delete(i + 1, i + 3);
                        i--;
                    }
                }
            }
        }
        if (sb.length() != 1 && sb.charAt(sb.length() - 1) == '/') {
            sb.delete(sb.length() - 1, sb.length());
        }
        return sb.toString();
    }
}
